let sdklistener = null;
let conlistener = null;
let messageListener = null;
let lastMessageId = null
var  ConNextSeg  = 0;
function initImSdk(){
	var tencentIm = api.require('tencentCloudChatSDK');
	tencentIm.initSDK({
		sdkAppID:1400773906,
		logLevel:6
	}, function(ret, err){
	    if(!ret){
	        api.toast({msg:err.desc});
	    }
	});
}

function  initStorage(userId){
	tencentCloudChat.initTencentCloudChat(api.require('tencentCloudChatSDK'))
}


async function userLogin(userId,userSig,callback){
	await tencentCloudChat.login({
		userID:userId.toString(),
		userSig:userSig
	}).catch(function(res){
		api.toast({msg:"登录失败:" + res.desc});
	}).then(function(res){
		if(res && res.data.code == 0){
			callback && callback.call(this,res);
		}
	})
}

function userLogout(callback){
	var tencentIm = api.require('tencentCloudChatSDK');
	tencentIm.logout({}, function(ret, err) {
	    if (ret) {
	        callback && callback.call(this)
	    } else {
	        api.toast({msg:"退出失败:" + ret.desc});
	    }
	});
}

function setEvent(userId){
	if(!userId){
		return;
	}
	var message = ''
	sdklistener = new sdkListener({
	    onConnectFailed:function(data){

		}, //SDK 连接腾讯云服务器失败
	    onKickedOffline:function(data){
			message = '您的账号已在其他设备登录！'
			_logout()
			api.alert({
			    title: '掉线提醒',
			    msg:message
			}, function(ret, err) {
				_login()
			});
		},
	    onUserSigExpired:function(data){
			message = '您的登录状态已经失效,请重新登录'
			_logout()
			api.alert({
			    title: '掉线提醒',
			    msg:message
			}, function(ret, err) {
				_login()
			});
		}
	})
	tencentCloudChat.addIMSDKListener(sdklistener)
	conlistener = new conversationListener({
	    onSyncServerStart:function(data){
			api.showProgress({});
		}, //同步服务器会话开始，SDK 会在登录成功或者断网重连后自动同步服务器会话，您可以监听这个事件做一些 UI 进度展示操作。
	    onSyncServerFinish:function(data){
			api.hideProgress();
		}, //同步服务器会话完成，如果会话有变更，会通过 onNewConversation | onConversationChanged 回调告知客户
	    onSyncServerFailed:function(data){
			api.hideProgress();
		}, //同步服务器会话失败
	    onNewConversation:function(data){
			console.log("收到消息3333333333"+ JSON.stringify(data))
			
		}, //有新的会话（比如收到一个新同事发来的单聊消息、或者被拉入了一个新的群组中），可以根据会话的 lastMessage -> timestamp 重新对会话列表做排序
	    onConversationChanged:function(data){
			console.log("关键信息发生变化"+ JSON.stringify(data))
			var uid = $api.getStorage('userid');
			if(data.data && data.data.length >0){
				data.data.map(function(value){
					getUserInfos(value.userID,null,true)
				})
			}
			// ConNextSeg = 0
			api.execScript({
			    name: 'xiaoxi_win',
			    frameName:'tri_0',
			    script:'getNowMsgList(1);'
			});	
		
				
		}, //某些会话的关键信息发生变化（未读计数发生变化、最后一条消息被更新等等），可以根据会话的 lastMessage -> timestamp 重新对会话列表做排序
	    onTotalUnreadMessageCountChanged:function(data){
			//console.error("全部会话未读总数变更的通知"+ JSON.stringify(data))
			var total = data.data;
			if(!$api.getStorage('shang')){
				api.setAppIconBadge({badge:total});
			}
			var msgNum = {
			    cnum:total,
			    mnum:0
			}
			$api.setStorage('msgNum', msgNum);
			_send('msgNum', msgNum);
		}, //全部会话未读总数变更的通知
	    onUnreadMessageCountChangedByFilter:function(data){

		} //根据 filter 过滤的未读消息总数变更通知（7.0 及以上版本支持）
	})
	tencentCloudChat.addConversationListener(conlistener)

	messageListener = new advancedMsgListener({
	    onRecvNewMessage:function(data){
			console.log( "[收到新消息]" + JSON.stringify( data ))
			//
			
			// console.log( "[用户信息]" +  $api.getStorage('sex'))
			try{
				if(data.data.cloudCustomData == 'diyEvent'){
					var eventData = JSON.parse(data.data.customElem.data)
					actionEvent(eventData);
				}else{
					// 投递消息
					var messages = JSON.parse(data.data.customElem.data);
					console.log("[收到新消息]" , JSON.stringify(messages))
					console.log("[收到新消息]" , JSON.stringify(messages.content))
					var contentText = '';
					var xiao_score = messages.score ? messages.score : 0;
					var styles = 1;
					
					if(messages.type == 9){
						if(messages.content.status == 0){
							contentText = '[语音通话] 未接通';
						}else{
							contentText = '通话时长 ' + getAudioAndVideoTime(messages.content.end,messages.content.start);
							xiao_score = messages.content.score;
						}
					}else if(messages.type == 10){
						if(messages.content.status == 0){
							contentText = '[视频通话] 未接通';
						}else{
							// console.log("[api/member/createMicDeduction]" , messages.content.orderid)
							

							contentText = '通话时长 ' + getAudioAndVideoTime(messages.content.end,messages.content.start);
							xiao_score = messages.content.score;
						}
					}else if(parseInt(messages.type) == -3){
					
						contentText = '<span style="color: red">[对方发来搭讪红包]<img style="position: relative;top: 10px;width: 32px;" src="../../res/img/emotion/Expression_106.png" alt=""></span>' ;
						var styles = 2;
					
					}
					if(lastMessageId == data.data.msgID){
						console.log("_______[消息重叠了]——————————")
						return
					}
					if(!lastMessageId || lastMessageId != data.data.msgID){
						lastMessageId = data.data.msgID
					}
					// api.execScript({
					// 	name: 'xiaoxi_win',
					// 	frameName:'tri_0',
					// 	script:'getNowMsgList(1);'
					// });	
					_send('newmsg',{
						data:{
							new:[
								{
									msgID:data.data.msgID,
									add_time:data.data.timestamp,
									time:getdate(data.data.timestamp),
									userid:data.data.userID,
									name:data.data.friendRemark ? data.data.friendRemark: data.data.nickName,
									showtime:true,
									cover:messages.cover ? messages.cover : '',
									score:xiao_score,
									styles:styles,
									second : messages.second ? messages.second : '',
									id : messages.id ? messages.id : '',
									head_portrait:data.data.faceUrl,
									content:messages.type == 9 || messages.type == 10 ? contentText :messages.content,
									data:messages.type == 9 || messages.type == 10 ? messages.content : messages.data,
									type:messages.type,
									self:data.data.isSelf ? 1 : 0,
									isRead:data.data.isRead ? 1 : 0,
									k:messages.k ? messages.k : 0,
									is_burn:0,
									status:0
								}
							],
							users:{
								touserid:data.data.userID,
								userid:data.data.userID,
								intimate:0
							}
						}
					})
					
					var dialogueUserid = $api.getStorage('dialogueUserid');
					if(!dialogueUserid || dialogueUserid != data.data.userID){
						setWarnning()
					}

				}
			}catch(e){
				//console.error("收到消息报错拉"+e)
			}
		}, // 收到新消息
	    onRecvMessageReadReceipts:function(data){
			//console.error( "[消息已读回执通知]" + JSON.stringify( data ))
			if(data.data.length > 0){
				for(var i=0;i<data.data.length;i++){
					_send('changeread',{
						result:{
							touserid:data.data[i].userID
						}
					})
				}
			}
		}, //消息已读回执通知（如果自己发送的消息支持已读回执，消息接收端调用 sendMessageReadReceipts，自己会收到该通知）
	    onRecvC2CReadReceipt:function(data){
			//console.error( "[对端用户会话已读通知]" + JSON.stringify( data ))
			if(data.data.length > 0){
				for(var i=0;i<data.data.length;i++){
					_send('changeread',{
						result:{
							touserid:data.data[i].userID
						}
					})
				}
			}
		}, //C2C 对端用户会话已读通知（如果对端用户调用 markC2CMessageAsRead 接口，自己会收到该回调，回调只会携带对端 userID 和对端已读 timestamp 信息）
	    onRecvMessageRevoked:function(data){
			//console.error( "[收到消息撤回的通知]" + JSON.stringify( data ))
			_send('revokeMessage',{msgID:data.data})
		}, //收到消息撤回的通知
	    onRecvMessageModified:function(data){
			//console.error( "[消息内容被修改]" + JSON.stringify( data ))
		},//消息内容被修改
	    onRecvMessageExtensionsChanged:function(data){

		},//消息扩展信息更新
	    onRecvMessageExtensionsDeleted:function(data){

		},//消息扩展信息被删除
	})
	tencentCloudChat.addAdvancedMsgListener(messageListener);
	//console.error(" ________________-- 监控——————————————————————————————————")
}

function removeEvents(){
	tencentCloudChat.removeIMSDKListener(sdklistener).catch(function(res){
		// console.error("事件退出" + JSON.stringify( res ))
	}).then(function(res){
		// console.error("事件退出ok" + JSON.stringify( res ))
	})
	tencentCloudChat.removeConversationListener(conlistener).catch(function(res){
		// console.error("事件退出" + JSON.stringify( res ))
	}).then(function(res){
		// console.error("事件退出ok" + JSON.stringify( res ))
	})
	tencentCloudChat.removeAdvancedMsgListener(messageListener).catch(function(res){
		// console.error("事件退出" + JSON.stringify( res ))
	}).then(function(res){
		// console.error("事件退出ok" + JSON.stringify( res ))
	})
}


function getConversations(prepose,success,error){


	console.log('最后一条数据',ConNextSeg)
	prepose && prepose.call(this)
	//tencentCloudChat.getConversationList({nextSeq:ConNextSeg,count:10}).catch(function(data){
	tencentCloudChat.getConversationList({count:40}).catch(function(data){
		console.log('错误信息',error)
		error && error.call(this)
	}).then(function(res){
		console.log( 'res数据',JSON.stringify(  res.data  ))
		if(res.data && res.data.data){
			// ConNextSeg  =  res.data.data.nextSeq
		
			ConNextSeg  =  parseInt(res.data.data.nextSeq)
		}
		//ConNextSeg  =  parseInt(res.data.data.nextSeq)
		// ConNextSeg  =  res.data.data.nextSeq
		success && success.call(this,res.data.data.conversationList)
		
		console.log( '列表数据222222222',JSON.stringify(  res.data.data  ))
	})
}

function sendCustom(touserId,data,priority){
	tencentCloudChat.createCustomMessage({data:data}).catch(function(error){
		// console.error("发送消息错误：" + JSON.stringify( error ))
	}).then(function(data){
		// console.error("succ：" + JSON.stringify( data ))
		if(data && data.data.code == 0){
			tencentCloudChat.sendMessage({
				id:data.data.data.id,
				receiver:touserId.toString(),
				onlineUserOnly:false,
				priority:typeof(priority) == 'number' ? priority : 0,
				groupID:'',
				cloudCustomData :'',
				localCustomData : '',
				isExcludedFromUnreadCount : false,
				isExcludedFromLastMessage : false,
				isSupportMessageExtension : false,
				needReadReceipt : false,
				offlinePushInfo : {}
			}).catch(function(error){
				// console.error("发送消息错误：" + JSON.stringify( error ))
				_msg(error.desc)
			}).then(function(datas){
				// console.error("succ：" + JSON.stringify( datas  ))
				if(datas && datas.data.code == 0){
					if(typeof(priority) == 'function'){
						priority.call(this,datas.data)
					}

				}
			})
		}
	})
}






function getUserInfos(touserId,callback,isUpdate){
	var userId = $api.getStorage('userid'),touserInfo = $api.getStorage('u_' + touserId);

	var touserInfoData = _getStorage('to_user_' + touserId);

	console.log('缓存个人数据',touserInfoData)

	if(touserInfoData){
		callback && callback.call(this,touserInfoData);
		return
	}
		
	if(!touserInfo || isUpdate){
		_ajax('api/message/getuserInfo', function(ret, err) {
			if(ret){
				
				_setStorage('to_user_' + ret.userid,ret);
				//$api.setStorage('u_' + ret.userid,ret);
				callback && callback.call(this,ret);
			}
		}, {
			userId:$api.getStorage('userid'),
			touserId:touserId
		})
	}else{
		callback && callback.call(this,touserInfo);
	}
}

function gettimestamp(){
	var date = new Date(); // 使用 ISO 8601 格式指定日期
	var timestamp = parseInt(date.getTime() / 1000);
	return timestamp;
}
function getdate(times){
	times = parseInt(times)
	var currtime = gettimestamp(),lastTime = currtime - times
	if(lastTime <= 10){
		return '刚刚';
	}else if(lastTime < 60){
		return lastTime + '秒前';
	}else if(lastTime < 3600){
		return (lastTime / 60).toFixed(0) + "分钟前";
	}else if( currtime > times + 21600){
		return timestampTranDate(times,0);
	}
	return timestampTranDate(times,1);
}

function timestampTranDate(value,type){
	var date = new Date(parseInt(value) * 1000);
	var Y = date.getFullYear();
	var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
	var D = date.getDate();
	var h = date.getHours();
	var m = date.getMinutes();
	var s = date.getSeconds();
	if(type == 1){
		return `${h}:${m}:${s}`;
	}else if(type == 2){
		return `${Y}-${M}-${D}`;
	}
	return `${Y}-${M}-${D} ${h}:${m}:${s}`;
}


function getConversaFieldText(data){
	try{
		if(!data){
			return '';
		}
		basedata = JSON.parse(data)
		switch(parseInt(basedata.type)){
			case 0:
				return basedata.content
			case -3:
				return '<span style="color: red">[对方发来搭讪红包]<img style="position: relative;top: 10px;width: 32px;" src="../../res/img/emotion/Expression_106.png" alt=""></span>'
			break;
			case 1:
				return '[图片]';
			break;
			case 2:
				return '[语音]';
			break;
			case 3:
				return '[视频]';
			break;
			case 8:
				return '[礼物]';
			break;
			case 9:
				return '[语音通话]';
			break;
			case 10:
				return '[视频通话]';
			break;
		}
	}catch(e){

	}
	return '';
}



async function markAllMessageAsRead(){
	let data = await tencentCloudChat.markAllMessageAsRead({})
}

function setMessageRead(userId,callback){
	tencentCloudChat.markC2CMessageAsRead({"userID":userId.toString()}).then(callback).catch(callback)
}

function deleteConversation(userId,callback){
	console.log(userId)
	tencentCloudChat.deleteConversation({conversationID:userId.toString()}).catch(function(error){
		//console.log(JSON.stringify( error ))
		_msg('删除失败');
	}).then(function(data){
		console.log( 'data:' + JSON.stringify( data ))
		if(data && data.data.code == 0){
			callback && callback.call(this)
		}
	})
}

function getTotalUnreadMessageCount(){
	tencentCloudChat.getTotalUnreadMessageCount({}).then(function(data){
		if(data && data.code == 0){
			var total = data.data;
			if(!$api.getStorage('shang')){
				api.setAppIconBadge({badge:total});
			}
			var msgNum = {
			    cnum:total,
			    mnum:0
			}
			$api.setStorage('msgNum', msgNum);
			_send('msgNum', msgNum);
		}
	})
}

function getAudioAndVideoTime(timestamp1,timestamp2){
	let difference = parseInt(timestamp1) - parseInt(timestamp2);
	if(difference < 1){
		//console.error("时间计算错误")
		return '00:00';
	}
	let minutes = (difference / 60).toString();
	if(minutes.indexOf('.') > -1){
		minutes = parseInt(minutes.substr(0,minutes.indexOf('.')));
	}
	if(minutes > 0){
		var seconds = difference - (minutes * 60);
	}else{
		var seconds = difference;
	}

	return (minutes < 10 ? ("0" + minutes) : minutes) + ':' + (seconds < 10 ? ("0" + seconds) : seconds);
}

function getC2CHistoryMessageList(touserId,lastMsgID,callback){
	if(callback && callback.load) callback.load.call(this)
	var uid = $api.getStorage('userid');
	// var getHistoryMessageList = _getStorage('getHistoryMessageList' + touserId +uid)
	// console.log('缓存数据',JSON.stringify( getHistoryMessageList))
	// getHistoryMessageList = '';
	// console.log('缓存key2222','getHistoryMessageList' + touserId +uid)
	// console.log('获取历史记录开始时间',gettimestamp());
	var queryData = {
		"userID":touserId.toString(),
		"count":10,
		getType:3
	};
	if(lastMsgID){
		queryData.lastMsgID = lastMsgID
	}
	tencentCloudChat.getHistoryMessageList(queryData).catch(function(res){
		if(callback && callback.finish) callback.finish.call(this)
		//console.error("[拉取历史消息]Error:" + JSON.stringify( res ))
		res.desc && _msg(res.desc)
	}).then(function(res){
		
		if(callback && callback.finish) callback.finish.call(this)
		//console.error("[拉取历史消息]OK:" + JSON.stringify( res.data.data ))
		if(res && res.data.code == 0){
		
			_setStorage('getHistoryMessageList' + touserId +uid,res.data.data)
			if(callback && callback.success) callback.success.call(this,res.data.data)
		}
	})

	
}

function resultMessageArray(data){
	try{
		var messages = JSON.parse(data.customElem.data);
		var contentText = '';
		var xiao_score = messages.score ? messages.score : 0;
		if(messages.type == 9){
			if(messages.content.status == 0){
				contentText = '[语音通话] 未接通';
			}else{
				contentText = '通话时长 ' + getAudioAndVideoTime(messages.content.end,messages.content.start);
				xiao_score =  messages.content.score
			}
		}else if(messages.type == 10){
			if(messages.content.status == 0){
				contentText = '[视频通话] 未接通';
			}else{
				contentText = '通话时长 ' + getAudioAndVideoTime(messages.content.end,messages.content.start);
				xiao_score =  messages.content.score
			}
		}else if(parseInt(messages.type) == -3){
			contentText = '<span style="color: red">[对方发来搭讪红包]<img style="position: relative;top: 10px;width: 32px;" src="../../res/img/emotion/Expression_106.png" alt=""></span>' ;
		}
		return {
			msgID:data.msgID,
			add_time:data.timestamp,
			time:getdate(data.timestamp),
			userid:data.userID,
			name:data.friendRemark ? data.friendRemark: data.nickName,
			showtime:true,
			score:xiao_score,
			second : messages.second ? messages.second : '',
			id : messages.id ? messages.id : '',
			head_portrait:data.faceUrl,
			cover:messages.cover ? messages.cover : '',
			content:messages.type == 9 || messages.type == 10 ? contentText :messages.content,
			data:messages.type == 9 || messages.type == 10 ? messages.content : messages.data,
			type:messages.type,
			self:data.isSelf ? 1 : 0,
			isRead:data.isPeerRead ? 1 : 0,
			k:messages.k ? messages.k : 0,
			is_burn:0,
			status:data.status == 6 ? 3 : 0
		}
	}catch(e){
		//console.error("【错误消息啊】" + e)
	}
	return false
}
